package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hy.corecode.idgen.WFGIdGenerator;
import io.xxx.xbutler.data.RobotRoomLogMapper;
import io.xxx.xbutler.data.RobotRoomMapper;
import io.xxx.xbutler.data.RoomMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.RobotRoom;
import io.xxx.xbutler.domain.RobotRoomLog;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.support.TransactionTemplate;

@Slf4j
public abstract class RobotLeaveRoomHandler implements CallbackHandler {

    @Resource
    protected WFGIdGenerator idGenerator;

    @Resource
    protected TransactionTemplate transactionTemplate;

    @Resource
    protected RoomMapper roomMapper;

    @Resource
    protected RobotRoomMapper robotRoomMapper;

    @Resource
    protected RobotRoomLogMapper robotRoomLogMapper;

    @Override
    public void handle(Callback callback) {
        String robotId = callback.getRobotId();
        JSONObject data = (JSONObject) callback.getData();
        String roomId = data.getString("vcChatRoomId");

        RobotRoomLog robotRoomLog = buildRobotRoomLog(callback);
        LambdaQueryWrapper<RobotRoom> robotRoomWrapper = new LambdaQueryWrapper<RobotRoom>()
                .eq(RobotRoom::getRobotId, robotId)
                .eq(RobotRoom::getRoomId, roomId);
        transactionTemplate.executeWithoutResult(_ -> {
            roomMapper.deleteById(roomId);
            robotRoomMapper.delete(robotRoomWrapper);
            robotRoomLogMapper.insert(robotRoomLog);
        });
    }

    protected abstract RobotRoomLog buildRobotRoomLog(Callback callback);
}
